package com.apobates.forum.trident.controller.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.trident.controller.form.BoardModeratorForm;
import com.apobates.forum.trident.controller.form.BoardModeratorPermissionForm;
import com.apobates.forum.core.api.service.BoardModeratorActionIndexService;
import com.apobates.forum.core.api.service.BoardModeratorRoleHistoryService;
import com.apobates.forum.core.api.service.BoardModeratorService;
import com.apobates.forum.core.entity.BoardModerator;
import com.apobates.forum.core.entity.BoardModeratorRoleHistory;
import com.apobates.forum.core.entity.ModeratorLevelEnum;
import com.apobates.forum.event.elderly.ForumActionEnum;
import com.apobates.forum.member.api.service.MemberService;
import com.apobates.forum.member.entity.Member;
import com.apobates.forum.utils.CommonBean;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.lang.EnumArchitecture;
/**
 * 版块版主控制器
 * 
 * @author xiaofanku@live.cn
 * @since 20190322
 */
@Controller
@RequestMapping(value = "/admin/board/moderator")
public class AdminBoardModeratorController {
	@Autowired
	private BoardModeratorService boardModeratorService;
	@Autowired
	private BoardModeratorActionIndexService boardModeratorActionIndexService;
	@Autowired
	private BoardModeratorRoleHistoryService boardModeratorRoleHistoryService;
	@Autowired
	private MemberService memberService;
	
	//所有版主|某版块的版主
	@GetMapping(path="/")
	public String boardModeratorPage(
			@RequestParam(name="board", required=false, defaultValue="0")long boardId, 
			@RequestParam(name="volume", required=false, defaultValue="0")int volumesId,
			HttpServletRequest request, 
			Model model) {
		Stream<BoardModerator> rs = (boardId>0)?boardModeratorService.getAllUsedByBoardId(volumesId, boardId):boardModeratorService.getAll();
		model.addAttribute("rs", rs.collect(Collectors.toList()));
		
		model.addAttribute("paramBoard", boardId);
		model.addAttribute("paramVolumes", volumesId);
		return "admin/board_moderator/index";
	}
	//编辑版主
	@GetMapping(path="/edit")
	public String boardModeratorForm(
			@RequestParam(name="id", required=false, defaultValue="0")long id,
			@RequestParam(name="board", required=false, defaultValue="0")long boardId,
			@RequestParam(name="volume", required=false, defaultValue="0")int volumesId,
			HttpServletRequest request, 
			Model model) {
		BoardModeratorForm form = new BoardModeratorForm();
		
		BoardModerator bm = boardModeratorService.get(id).orElse(BoardModerator.empty());
		form.setRecord(bm.getId());
		form.setStatus(bm.isStatus());
		//大版主
		form.setBoardId(bm.getBoardId()+"");
		form.setVolumesId(bm.getVolumesId()+"");
		form.setMemberId(bm.getMemberId()+"");
		form.setMemberNames(bm.getMemberNickname());
		form.setLevel(bm.getLevel());
		
		if(id==0 && boardId>0 ) {
			form.setBoardId(boardId+"");
		}
		if(id==0 && volumesId>0){
			form.setVolumesId(volumesId+"");
		}
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		//
		Map<Integer,String> levelData = EnumArchitecture.getInstance(ModeratorLevelEnum.class);
		model.addAttribute("levelData", levelData);
		return "admin/board_moderator/edit";
	}
	@PostMapping(path="/edit")
	public String boardModeratorAction(
			@ModelAttribute("form")BoardModeratorForm form,
			HttpServletRequest request, 
			Model model) {
		BoardModerator bm = new BoardModerator();
		bm.setVolumesId(form.getIntegerVolumes());
		bm.setBoardId(form.getLongBoard());
		bm.setMemberId(form.getLongMember());
		bm.setMemberNickname(form.getMemberNames());
		bm.setStatus(form.getBooleanStatus());
		bm.setLevel(form.getEnumLevel());
		
		boolean symbol=false; 
		String jumpLink = "/admin/board/moderator/?board="+bm.getBoardId()+"&volume="+bm.getVolumesId();
		String errMsg=null;
		try {
			if (form.isUpdate()) {
				symbol = boardModeratorService.edit(form.getLongRecord(), bm).orElse(false);
			} else {
				Member m = memberService.get(bm.getMemberId()).orElse(Member.empty(bm.getMemberId()));
				Optional<BoardModerator> rObj = boardModeratorService.create(bm.getVolumesId(), bm.getBoardId(), m, bm.getLevel());
				if (rObj.isPresent()) {
					symbol=true;
					jumpLink = "/admin/board/moderator/permission?id=" + rObj.get().getId(); // 进行授权
				}
			}
		} catch (IllegalStateException e) {
			errMsg = e.getMessage();
		}
		if(symbol) {
			return "redirect:"+jumpLink;
		}
		model.addAttribute("errors", Commons.optional(errMsg, form.getActionTitle()+"版主操作失败"));
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		//
		Map<Integer,String> levelData = EnumArchitecture.getInstance(ModeratorLevelEnum.class);
		model.addAttribute("levelData", levelData);
		return "admin/board_moderator/edit";
	}
	//指定版块下的
	@GetMapping(path="/json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<Long,String> getAllOfBoardForJson(@RequestParam(name="board", required=false, defaultValue="0")long boardId, HttpServletRequest request, Model model){
		Stream<BoardModerator> rs = (boardId>0)?boardModeratorService.getAllByBoardId(boardId):boardModeratorService.getAll();
		return rs.collect(Collectors.toMap(BoardModerator::getId, BoardModerator::getMemberNickname));
	}
	@GetMapping(path="/permission")
	public String permissionForm(@RequestParam("id")long moderatorId, HttpServletRequest request, Model model) {
		model.addAttribute("rs", getModeratorAllAction());
		String[] existsEnumSymbolArrayString = boardModeratorActionIndexService.getAllByBoardId(moderatorId).map(ForumActionEnum::getSymbol).map(Object::toString).toArray(String[]::new);
		//
		BoardModeratorPermissionForm form = new BoardModeratorPermissionForm();
		form.setToken(Commons.randomAlphaNumeric(8));
		form.setModeratorId(moderatorId+"");
		form.setActions(existsEnumSymbolArrayString);
		form.setRecord(Commons.isNotEmpty(existsEnumSymbolArrayString)?10:0);
		//
		model.addAttribute("form", form);
		return "admin/board_moderator/permission";
	}
	@PostMapping(path="/permission")
	public String permissionAction(@ModelAttribute("form")BoardModeratorPermissionForm form, HttpServletRequest request, Model model) {
		List<ForumActionEnum> actions = new ArrayList<>();
		for(String enumSymbol : form.getActions()) {
			try {
				Optional<EnumArchitecture> ins = EnumArchitecture.getInstance(Integer.valueOf(enumSymbol), ForumActionEnum.class);
				if(ins.isPresent()) {
					actions.add((ForumActionEnum)ins.get());
				}
			}catch(Exception e) {
				continue;
			}
		}
		Optional<Boolean> symbol=Optional.empty();
		String errMsg=null;
		try{
			if(form.isUpdate()) {
				if(!actions.isEmpty()) {
					symbol = boardModeratorActionIndexService.edit(Long.valueOf(form.getModeratorId()), actions);
				}
			}else {
				if(!actions.isEmpty()) {
					symbol = boardModeratorActionIndexService.grantModeratorActions(Long.valueOf(form.getModeratorId()), actions);
				}
			}
		}catch(IllegalStateException e){
			errMsg=e.getMessage();
		}
		if(symbol.isPresent()) {
			return "redirect:/admin/board/moderator/";
		}
		model.addAttribute("errors", Commons.optional(errMsg, form.getActionTitle()+"版主权限操作失败"));
		//
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		//
		model.addAttribute("rs", getModeratorAllAction());
		return "admin/board_moderator/permission";
	}
	
	@GetMapping(path="/roles")
	public String getModeratorRoleHistory(
			@RequestParam("member")long memberId,
			HttpServletRequest request, 
			Model model){
		List<BoardModeratorRoleHistory> data = boardModeratorRoleHistoryService.getByMember(memberId).collect(Collectors.toList());
		model.addAttribute("rs", data);
		//
		Member member = memberService.get(memberId).orElse(Member.robotMember());
		model.addAttribute("moderator", member);
		return "admin/board_moderator/role_history";
	}
	//board|topic|posts
	private Map<String,List<CommonBean>> getModeratorAllAction(){
		Map<String,List<CommonBean>> rs = new HashMap<>();
		//
		Set<ForumActionEnum> data = ForumActionEnum.getModeratorActions();
		for(ForumActionEnum fa : data){
			if(!rs.containsKey(fa.getSection())){
				rs.put(fa.getSection(), new ArrayList<>());
			}
			rs.get(fa.getSection()).add(new CommonBean(fa.getSymbol(), fa.getTitle()));
		}
		//
		return rs;
	}
	//版主卸任
	@PostMapping(path="/quit", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public TipMessage leaveJob(
			@RequestParam(name="member", required=false, defaultValue="0")long memberId,
			@RequestParam(name="board", required=false, defaultValue="0")long boardId,
			@RequestParam(name="volume", required=false, defaultValue="0")int volumesId,
			HttpServletRequest request, 
			Model model) {
		Optional<Boolean> symbol=Optional.empty();
		String errMsg=null;
		try{
			if(0==boardId){ //大版主
				symbol = boardModeratorService.remove(volumesId, memberId);
			}else{
				symbol = boardModeratorService.remove(volumesId, boardId, memberId);
			}
		}catch(IllegalStateException e){
			errMsg=e.getMessage();
		}
		if (symbol.isPresent()) {
			return TipMessage.ofSuccess("版主卸任成功");
		}
		return TipMessage.ofError(Commons.optional(errMsg, "操作失败"));
	}
}
